/*
 * Copyright (C) 2011 Johan Kannala
 *
 * Licensed under the MIT License. You can find a copy of the License at in the
 * license.txt file.
 */
package com.joppe.vocabtutor;

import android.app.*;
import android.content.*;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.widget.*;

/**
 * @author joppe
 * 
 */
public class ListWordsActivity extends LoggedActivity {
    // Edit word request.
    private static final int EDIT_WORD_REQUEST = 1;
    
    // Option items.
    private static final int ADD_WORDS = 1;
    private static final int DELETE_WORDS = 2;

    // Dialog identifiers.
    private static final int DELETE_WORDS_DLG = 2;

    private VocabTutor mApplication = null;
    private VocabTutorDBHelper mDBHelper = null;
    private Cursor mWordsCursor = null;
    private Long mBookId = null;
    private Long mChapterId = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mApplication = (VocabTutor) this.getApplication();
        mDBHelper = mApplication.getDataHelper();
        setContentView(R.layout.word_list);
        ListView wordList = (ListView) findViewById(R.id.word_list);
        wordList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> wordList, View item,
                    int position, long rowid) {
                Log.d("event",
                        "Word long-clicked: "
                                + wordList.getItemAtPosition(position));
                startEditWord(rowid);
                return false;
            }
        });
        LayoutInflater inflater = LayoutInflater.from(this);
        View header = inflater.inflate(R.layout.list_header, wordList, false);
        wordList.addHeaderView(header);
        updateFromIntent();
    }
    
    @Override
    public void onResume() {
        super.onResume();
        mWordsCursor.requery();
    }
    
    @Override
    public void onStop() {
        super.onStop();
        mWordsCursor.deactivate();
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        mWordsCursor.close();
    }
    
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        updateFromIntent();
    }
    
    private void updateFromIntent() {
        boolean newBook = false;
        boolean newChapter = false;
        Bundle extraInfo = getIntent().getExtras();
        if (extraInfo != null) {
            if (extraInfo.containsKey("book_id")) {
                Long newBookId = extraInfo.getLong("book_id");
                if (!newBookId.equals(mBookId)) {
                    newBook = true;
                    mBookId = newBookId;
                }
            }
            if (extraInfo.containsKey("chapter_id")) {
                Long newChapterId = extraInfo.getLong("chapter_id"); 
                if (!newChapterId.equals(mChapterId)) {
                    newChapter = true;
                    mChapterId = newChapterId;
                }
            }
        }
        if (mBookId == null || mChapterId == null) {
            throw new RuntimeException("Book or chapter id not provided to " +
                    "ListWordsActivity.");
        }
        SQLiteDatabase db = mApplication.getDataHelper().getReadableDatabase();
        // Update header book title if the book id has changed.
        if (newBook) {
            Cursor c = db.rawQuery("select title from books where _id = ?",
                        new String[] {mBookId.toString()});
            if (c.moveToFirst()) {
                ((TextView) findViewById(R.id.book_title)).setText(c.getString(0));
            }
            c.close();
        }
        // Update chapter title if the book id has changed.
        if (newChapter) {
            if (mWordsCursor != null) {
                mWordsCursor.close();
                mWordsCursor = null;
            }
            Cursor c = db.rawQuery("select title from chapters where _id = ?",
                    new String[] {mChapterId.toString()});
            if (c.moveToFirst()) {
                ((TextView) findViewById(R.id.chapter_title)).setText(c.getString(0));
            }
            c.close();
        }
        ListView wordList = (ListView) findViewById(R.id.word_list);
        mWordsCursor = db.query("words", new String[] { "_id", "word" },
                "chapter_fk = ?", new String[] { mChapterId.toString() },
                null, null, null);
        SimpleCursorAdapter ca = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_multiple_choice,
                mWordsCursor,
                new String[] { "word" },
                new int[] { android.R.id.text1 });
        wordList.setAdapter(ca);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == EDIT_WORD_REQUEST) {
            setIntent(data);
            updateFromIntent();
        }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(Menu.NONE, ADD_WORDS, Menu.NONE, "Add new word");
        menu.add(Menu.NONE, DELETE_WORDS, Menu.NONE, "Delete words");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case ADD_WORDS:
            long newWordId = mDBHelper.createNewWord(mChapterId);
            Intent i = new Intent(ListWordsActivity.this,
                    EditWordActivity.class);
            i.putExtra("book_id", mBookId);
            i.putExtra("chapter_id", mChapterId);
            i.putExtra("word_id", newWordId);
            startActivity(i);
            return true;
        case DELETE_WORDS:
            showDialog(DELETE_WORDS_DLG);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DELETE_WORDS: {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Delete words");
            builder.setMessage("Temp message");
            builder.setPositiveButton("Delete",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ListView wordList = (ListView) findViewById(R.id.word_list);
                            long[] selectedIds = wordList.getCheckItemIds();
                            String selectString = VocabTutor
                                    .toCommaSeparatedString(selectedIds);
                            Log.i("com.joppe.vocabtutor", selectString);
                            SQLiteDatabase db = null;
                            db = mApplication.getDataHelper()
                                    .getWritableDatabase();
                            db.delete("words", "_id in " + selectString, null);
                            mWordsCursor.requery();
                        }
                    });
            builder.setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Log.i("event_notification",
                                    "Word deletion cancelled");
                        }
                    });
            return builder.create();
        }
        }
        return super.onCreateDialog(id);
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch (id) {
        case DELETE_WORDS_DLG: {
            AlertDialog ad = (AlertDialog) dialog;
            ListView wordList = (ListView) findViewById(R.id.word_list);
            long[] selectedIds = wordList.getCheckItemIds();
            String selectString = VocabTutor
                    .toCommaSeparatedString(selectedIds);
            Cursor c = null;
            try {
                SQLiteDatabase db = mApplication.getDataHelper().getWritableDatabase();
                c = db.query("words", new String[] { "word" },
                        "_id in " + selectString, null, null, null, null);
                StringBuilder buf = new StringBuilder(
                        "Are you sure you want to delete the following words?");
                while (c.moveToNext()) {
                    buf.append('\n').append(c.getString(0));
                }
                ad.setMessage(buf.toString());
            }
            catch (Throwable t) {
                t.printStackTrace();
            }
            finally {
                if (c != null)
                    c.close();
            }
            break;
        }
        }
        super.onPrepareDialog(id, dialog);
    }
    
    private void startEditWord(long wordId) {
        Intent i = new Intent(ListWordsActivity.this, EditWordActivity.class);
        i.putExtra("book_id", mBookId);
        i.putExtra("chapter_id", mChapterId);
        i.putExtra("word_id", wordId);
        startActivityForResult(i, EDIT_WORD_REQUEST);
    }
}
